import Router from 'koa-router'
const router = new Router()

import redis from '../../utils/redis.js'

const DEVICE_PREFIX = 'webrtc:device:'
const ROOM_PREFIX = 'webrtc:room:'
const CALL_PREFIX = 'webrtc:call:'

// 获取房间列表（基础信息）
router.get('/rooms', async (ctx) => {
  const keys = await redis.keys(ROOM_PREFIX + '*')
  const rooms = []
  for (const key of keys) {
    const roomId = key.replace(ROOM_PREFIX, '')
    const members = await redis.hgetall(key)
    const deviceId = await redis.get(DEVICE_PREFIX + roomId)
    const inCall = await redis.hlen(CALL_PREFIX + roomId)
    rooms.push({
      id: roomId,
      name: roomId,
      participants: Object.keys(members).length,
      deviceId: deviceId || null,
      status: inCall > 0 ? 'active' : 'idle'
    })
  }
  ctx.body = { rooms }
})

// 房间详情
router.get('/rooms/:roomId', async (ctx) => {
  const { roomId } = ctx.params
  const roomKey = ROOM_PREFIX + roomId
  const members = await redis.hgetall(roomKey)
  const callMembers = await redis.hgetall(CALL_PREFIX + roomId)
  ctx.body = {
    id: roomId,
    members: Object.keys(members),
    callMembers: Object.keys(callMembers)
  }
})

// 释放设备绑定
router.post('/rooms/:roomId/release-device', async (ctx) => {
  const { roomId } = ctx.params
  await redis.del(DEVICE_PREFIX + roomId)
  ctx.body = { success: true }
})

// 解散房间（并结束通话）
router.delete('/rooms/:roomId', async (ctx) => {
  const { roomId } = ctx.params
  await redis.del(ROOM_PREFIX + roomId)
  await redis.del(CALL_PREFIX + roomId)
  ctx.body = { success: true }
})

// 结束房间通话
router.post('/rooms/:roomId/hangup', async (ctx) => {
  const { roomId } = ctx.params
  await redis.del(CALL_PREFIX + roomId)
  ctx.body = { success: true }
})

// 清理空房间
router.post('/rooms/cleanup-empty', async (ctx) => {
  const keys = await redis.keys(ROOM_PREFIX + '*')
  let cleaned = 0
  for (const key of keys) {
    const members = await redis.hgetall(key)
    if (Object.keys(members).length === 0) {
      await redis.del(key)
      cleaned++
    }
  }
  ctx.body = { success: true, cleaned }
})

export default router


